package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j

public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;

    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //参数检验
        if(dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus() != null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> iPage = page(page, wrapper);
        return new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
    }

    @GlobalTransactional(timeoutMills = 100000,rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //参数检查
        if(dto.getId()==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询当前认证用户是否在 APP端有当前用户
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getId, dto.getId());
        ApUserRealname apUserRealname = getOne(wrapper);
        if(apUserRealname == null){
            log.error("待审核 实名认证信息不存在   userRealnameId:{}",dto.getId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())){
            log.error("实名认证信息非待审核状态   userRealnameId:{}", dto.getId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId, apUserRealname.getUserId()));
        if(apUser == null){
            log.error("实名认证信息 关联 app的用户不存在    userRealnameId:{}, userId:{} ", dto.getId(), apUserRealname.getUserId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //更新认证用户信息
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        
        if(AdminConstants.PASS_AUTH.equals(status)){
            //创建自媒体账户
            WmUser wmUser = createWmUser(dto,apUser);
            //创建作者信息
            createAuthor(apUser,wmUser);
        }
        return ResponseResult.okResult();
    }

    //创建作者信息
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if(result.getCode().intValue() !=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }
        ApAuthor apAuthor = result.getData();

        if(apAuthor != null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        //如果不存在 创建作者信息
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2);//平台自媒体人
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult saveResult = articleFeign.save(apAuthor);
        if(saveResult.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }

    }


    //创建自媒体账户
    private WmUser createWmUser(AuthDTO dto, ApUser apUser) {
        //根据用户名查询 wmUser是否已经创建
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (result.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }
        WmUser wmUser = result.getData();

        if(wmUser != null){
            //已经创建 抛异常
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        //创建wmUser信息 保存
        wmUser = new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setApUserId(apUser.getId());//关联的app账户id
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> responseResult = wemediaFeign.save(wmUser);
        if (responseResult.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }
        return responseResult.getData();//返回保存成功的自媒体账户信息
    }
}
